package com.github.alfred.catchlog;


import com.github.alfred.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * ResponseHandler
 *
 * @author Frank Zhang
 * @date 2020-11-10 3:18 PM
 */
@Component
public class DefaultResponseHandler implements ResponseHandlerI{
    private static final Logger log= LoggerFactory.getLogger(DefaultResponseHandler.class);
    @Override
    public  Object handle(Class<?> returnType, String errCode, String errMsg){
        if (isColaResponse(returnType)) {
            return handleColaResponse(returnType, errCode, errMsg);
        }
        return null;
    }

    private static Object handleColaResponse(Class<?> returnType, String errCode, String errMsg) {
        try {
            Result<?> response = (Result<?>)returnType.newInstance();
            response.setCode(Result.FAIL_CODE);
            response.setErrorCode(errCode);
            response.setMsg(errMsg);
            return response;
        }
        catch (Exception ex){
            log.error(ex.getMessage(), ex);
            return  null;
        }
    }

    private static boolean isColaResponse(Class<?> returnType) {
        return  returnType == Result.class || returnType.getGenericSuperclass() == Result.class;
    }
}
